<template>
  <m-modal
    v-model="visible"
    title="文件恢复"
    class="v-restore-backup"
    :width="736"
    :height="630"
    mask
    @cancel="handleCancel"
  >
    <div ref="content" class="_content">
      <div v-if="showWarning" class="warn">
        <a-icon type="close-circle" theme="filled"/>
        <span>自动保存失败！请及时恢复历史文件，以免丢失工作进度！</span>
      </div>
      <div class="_header">
        显示文件范围：最近
        <a-input-number
          v-model="showDays"
          style="width: 64px; margin:0 4px"
          :min="1"
        />
        天
      </div>
      <div class="_table-container" :style="{height: showWarning ? 'calc(100% - 68px)' : 'calc(100% - 44px)'}">
        <a-table
          class="table-area"
          :data-source="tableDataFiltered"
          :bordered="true"
          :pagination="false"
          rowKey="id"
          :scroll="{ y: scrollY }"
          :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange, hideDefaultSelections: true}">

          <a-table-column dataIndex='time' title="保存时间"/>
          
          <a-table-column dataIndex='fileName' title="文件名"/>
         
          <a-table-column dataIndex='sizeStr' title="文件大小"/>

          <a-table-column dataIndex='saveTypeName' title="保存类型"/>
          
        </a-table>
      </div>
    </div>
    <template #footer>
      <a-button :disabled="removeDisabled" class="g-m-r-12" @click="handleRemove">
        删除
      </a-button>
      <a-button :disabled="restoreDisabled"  type="primary" :loading="saveLoading" @click="handleRestore">
        恢复
      </a-button>

    </template>
  </m-modal>
</template>
<script>
import { Portal } from "src/components/common/Portal.vue";
import Modal from "src/components/common/CustomModal";
import { storage } from "src/util/common";
import { BackupService, SaveType } from "@/util/BackupManager";
import localFile from "@/util/localFile";

const com = {
  name: "comp-restore-backup",
  components: {
    "m-modal": Modal,
  },
  props: {
    //// projectFullPath: String,
    projectConfig: {
      type: Object, //// 必须有字段： id:string, modified:boolean, projectFullPath:string
      required: true,
      validator(val){
        return val && val.id && val.projectFullPath;

      }
    },
    showWarning: Boolean

  },
  data() {
    return {
      visible: false,
      saveLoading: false,
      showDays: 3,
      selectedRowKeys: [],
      //// showWarning: false,
      tableData: [],
      scrollY: this.showWarning ? 400 - 24 : 400,
      nowStamp: Date.now()
    };
  },
  computed: {
    tableDataFiltered(){
      const timeLength = this.showDays * 24 * 60 * 60 * 1000;
      return this.tableData.filter(it => this.nowStamp - it.timeStamp < timeLength);
    },
    removeDisabled(){
      return this.selectedRowKeys.length === 0;
    },
    restoreDisabled(){
      return this.selectedRowKeys.length !== 1;
    }

  },
  created() {
    this.loadBackupList();
    
  },
  mounted() {
    this.visible = true;
    //// const content = this.$refs['content'];
    //// this.$nextTick(() => {
    ////   const tableContainer = content.querySelector('._table-container');
    ////   this.scrollY = tableContainer.offsetHeight - 15 * 2 - 30;
    //// });

  },
  methods: {
    handleOk(res) {
      this.visible = false;
      this.$emit("sure", res);
    },
    handleCancel(e) {
      this.visible = false;
      this.$emit("close", e);
    },
    loadBackupList(){
      this.tableData = BackupService.getBackupItemList(this.projectConfig.projectFullPath);

    },

    onSelectChange(keys) {
      console.log(keys);

      this.selectedRowKeys = keys;
      
    },
    handleRemove(){
      
      const toRemoveItemPaths = this.tableDataFiltered.filter(i => this.selectedRowKeys.includes(i.id)).map(i => i.filePath);
      toRemoveItemPaths.forEach(filePath => {
        BackupService.removeBackup(filePath);

      });
      this.tableData = this.tableData.filter(i => !this.selectedRowKeys.includes(i.id));
      this.selectedRowKeys = [];

    },
    handleRestore(){
      const targetKey = this.selectedRowKeys[0];
      if (!targetKey) return;
      this.saveLoading = true;
      const backupItem = this.tableDataFiltered.find(i => i.id === targetKey);
      BackupService.restoreBackup(this.projectConfig, backupItem).then(() => {
        app.$messageBox.success({ text: '恢复成功' });
        this.handleOk();
      }).catch(e => {
        app.$messageBox.error({ text: '恢复失败' });
        console.error(e);

      }).finally(() => {
        this.saveLoading = false;
      });
    }

  },
};

export default com;
export const restoreBackup = new Portal(com);
export const portal = restoreBackup;
</script>
<style lang="scss" scoped>
.v-restore-backup {
  .warn {
    color: #E72829;
    line-height: 24px;
    display: flex;
    align-items: center;
    > i {
      font-size: 14px;
    }
    > span {
      margin-left: 5px;
    }
  }
  ._content {
    padding: 22px;
    height: 100%;
	._header {
    height: 44px;
    background: #D4EBF8;
    border: 1px solid #B1CEE2;
    display: flex;
    align-items: center;
    padding-left: 8px;
	}
  ._table-container {
    padding: 15px 10px;
    border: 1px solid rgba(0, 0, 0, 0.15);
    border-top: 0;
    .table-area {
      /deep/ .ant-table {
        th, td {
          padding: 4px 8px;
          border-radius: 0;
        }
        .ant-table-body {
          overflow-y: auto !important;
          table {
            border-radius: 0;
          }
        }
        .ant-table-thead {
          .ant-table-selection-column .ant-table-header-column {
            display: none;
          }
        }
      }
    }
  }
  }
  
}
</style>
